package com.asen.commons.core.concurrent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.transaction.support.TransactionSynchronization;

/**
 * TransactionSynchronization
 *
 * @author Gary
 * @version 1.0
 * @date 2021-02-01
 */
@Slf4j
public abstract class TransactionAdapter<T> implements TransactionSynchronization, Ordered {

    @Override
    public final int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    @Override
    public final void suspend() {
    }

    @Override
    public final void resume() {
    }

    @Override
    public final void flush() {
    }

    @Override
    public final void beforeCommit(boolean readOnly) {
    }

    @Override
    public final void beforeCompletion() {
    }

    @Override
    public final void afterCommit() {
        try {
            commit();
        } catch (Exception e) {
            try {
                log.error("commit new transaction failed.", e);
                rollback();
            } catch (Exception ex) {
                log.error("rollback new transaction failed.", ex);
            }
        }
    }

    /**
     * 提交处理方法
     *
     * @throws Exception
     */
    abstract protected void commit() throws Exception;

    /**
     * 回滚处理方法
     *
     * @throws Exception
     */
    protected void rollback() throws Exception {

    }

    @Override
    public final void afterCompletion(int status) {
    }

}
